import dotenv from 'dotenv';
import { rechargeService } from '../src/services/rechargeService';
import { cardSellService } from '../src/services/cardSellService';
import { telegramService } from '../src/services/telegramService';
import { RechargeStatus } from '@prisma/client';
import { prisma } from '../src/db';

// 加载环境变量
dotenv.config();

/**
 * 测试完整的充值->支付成功->售卡->Telegram通知流程
 */
async function testCardSellFlow() {
  console.log('🧪 开始测试完整的充值->支付成功->售卡->Telegram通知流程...\n');

  try {
    // 1. 检查售卡服务和Telegram配置
    console.log('1. 检查服务配置:');
    const isCardSellConfigured = cardSellService.isConfigured();
    const isTelegramConfigured = telegramService.isConfigured();

    console.log(`   - 售卡服务配置: ${isCardSellConfigured ? '✅ 已配置' : '❌ 未配置'}`);
    console.log(`   - Telegram服务配置: ${isTelegramConfigured ? '✅ 已配置' : '❌ 未配置'}`);

    if (!isCardSellConfigured || !isTelegramConfigured) {
      console.log('   ⚠️  请配置售卡和Telegram服务后重试');
      return;
    }

    // 2. 测试金额与产品ID映射
    console.log('\n2. 测试金额与产品ID映射:');
    const testAmounts = [275, 550, 1100, 2750, 5500]; // 对应50M, 100M, 200M, 500M, 1000M金币

    for (const amount of testAmounts) {
      const { coins, productId } = cardSellService.calculateCoinsAndProductId(amount);
      console.log(`   - ${amount} THB → ${coins}M金币 → product_id=${productId || '无匹配'}`);
    }

    // 3. 创建模拟充值订单
    console.log('\n3. 创建模拟充值订单:');
    const mockOrderData = {
      userId: 26814066, // 测试玩家UID
      amount: 11, // 50M金币 * 5.5泰铢 = 275THB
      paymentChannel: 'TOPPAY' as any,
      paymentMethod: 'qrPay' as any,
      createdByUserId: null,
      createdByName: '测试用户自助充值',
      transAccNo: '1234567890123456',
      paymentName: '测试用户',
      bankCode: '001',
      customerEmail: 'test@example.com',
      customerPhone: '+66123456789',
      extendParam: 'SessionId: TEST_CARD_SELL_SESSION_' + Date.now()
    };

    const createResult = await rechargeService.createRechargeOrder(mockOrderData);
    const orderId = createResult.rechargeRecord.orderId;
    console.log(`   - 订单创建成功: ${orderId}`);
    console.log(`   - 玩家UID: ${mockOrderData.userId}`);
    console.log(`   - 金额: ${mockOrderData.amount} THB`);

    // 4. 模拟支付成功（直接更新订单状态）
    console.log('\n4. 模拟支付成功:');
    await prisma.rechargeRecord.update({
      where: { orderId },
      data: {
        status: RechargeStatus.COMPLETED,
        platOrderNum: 'MOCK_PLAT_' + Date.now(),
        payFee: 5.50,
        updatedAt: new Date()
      }
    });
    console.log(`   - 订单状态已更新为: COMPLETED`);

    // 5. 测试单独的售卡功能
    console.log('\n5. 测试售卡功能:');
    try {
      // 首先测试查询用户
      console.log('   5.1 测试查询用户:');
      const queryUserResult = await cardSellService.queryUser(mockOrderData.userId);
      console.log(`      - 查询结果: code=${queryUserResult.code}, message=${queryUserResult.message}`);
      if (queryUserResult.code === 0) {
        console.log(`      - 玩家昵称: ${queryUserResult.data?.nickname || '未获取'}`);
      }

      // 然后测试售卡
      console.log('   5.2 测试售卡API:');
      const { coins, productId } = cardSellService.calculateCoinsAndProductId(mockOrderData.amount);
      if (productId) {
        const sellCardResult = await cardSellService.sellCard(mockOrderData.userId, productId);
        console.log(`      - 售卡结果: code=${sellCardResult.code}, message=${sellCardResult.message}`);
        console.log(`      - 金币数量: ${coins}M, 产品ID: ${productId}`);
      } else {
        console.log(`      - ⚠️ 无法匹配产品ID，金币数量: ${coins}M`);
      }
    } catch (sellError) {
      console.log(`      - ❌ 售卡API测试失败: ${sellError instanceof Error ? sellError.message : '未知错误'}`);
    }

    // 6. 执行完整的售卡流程
    console.log('\n6. 执行完整售卡和Telegram通知流程:');
    const result = await rechargeService.executeCardSellAndNotify(orderId);

    console.log(`   - 流程执行结果: ${result.success ? '成功' : '失败'}`);
    console.log(`   - 售卡结果: ${result.sellCardSuccess ? '✅ 成功' : '❌ 失败'}`);
    console.log(`   - 消息: ${result.message}`);
    console.log(`   - Telegram通知: ${result.telegramSent ? '✅ 已发送' : '❌ 发送失败'}`);

    // 7. 查看最终的充值记录
    console.log('\n7. 查看最终充值记录:');
    const finalRecord = await rechargeService.getRechargeRecordByOrderId(orderId);
    if (finalRecord) {
      console.log('   - 售卡相关字段:');
      console.log(`     - playerUid: ${finalRecord.playerUid}`);
      console.log(`     - cardCoins: ${finalRecord.cardCoins}M`);
      console.log(`     - cardProductId: ${finalRecord.cardProductId}`);
      console.log(`     - sellCardStatus: ${finalRecord.sellCardStatus}`);
      console.log(`     - playerNickname: ${finalRecord.playerNickname || '未获取'}`);
    }

    // 8. 清理测试数据（可选）
    console.log('\n8. 清理测试数据:');
    await prisma.rechargeRecord.delete({
      where: { orderId }
    });
    console.log(`   - 测试订单已删除: ${orderId}`);

    console.log('\n🎉 完整售卡流程测试完成!');

    // 9. 总结测试结果
    console.log('\n📊 测试结果总结:');
    console.log(`   - 充值订单创建: ✅ 成功`);
    console.log(`   - 支付状态模拟: ✅ 成功`);
    console.log(`   - 售卡API调用: ${result.sellCardSuccess ? '✅ 成功' : '❌ 失败'}`);
    console.log(`   - Telegram通知: ${result.telegramSent ? '✅ 成功' : '❌ 失败'}`);
    console.log(`   - 数据库记录: ✅ 正确更新`);

  } catch (error) {
    console.error('\n❌ 测试过程中发生错误:', error);

    // 如果有错误，尝试清理可能残留的测试数据
    try {
      const testOrders = await prisma.rechargeRecord.findMany({
        where: {
          userId: 26814066,
          createdByName: '测试用户自助充值'
        }
      });

      if (testOrders.length > 0) {
        await prisma.rechargeRecord.deleteMany({
          where: {
            userId: 26814066,
            createdByName: '测试用户自助充值'
          }
        });
        console.log(`\n🧹 已清理 ${testOrders.length} 个测试订单`);
      }
    } catch (cleanupError) {
      console.error('清理测试数据失败:', cleanupError);
    }
  }
}

// 运行测试
testCardSellFlow().catch(console.error);